package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.Dept;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.assertj.core.util.Sets;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description UserServiceImpl
 * @Author apeng
 * @Date 2024-10-24
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final DeptMapper deptMapper;

    private final UserRoleMapper userRoleMapper;

    //用户管理分页查询
    @Override
    public ResponseResult<PageResponse<UserVo>> findUserVoPage(UserDto userDto, Integer pageNum,
                       Integer pageSize) {
        if(!ObjectUtil.isEmpty(userDto.getDeptNo())){
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<UserVo> page = userMapper.findUserVoPage(userDto);
        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);
        List<UserVo> voList = page.getResult();
        voList.forEach(userVo -> {
            //查出所有的角色的id
            Set<String> roleVoId = userMapper.getRoleVoId(userVo.getId());
            userVo.setRoleVoIds(roleVoId);
            //根据查出的id将角色的名字查出来
            Set<String> roleLables = userMapper.getRoleLabels(roleVoId);
            userVo.setRoleLabels(roleLables);
        });
        pageResponse.setRecords(voList);
        return ResponseResult.success(pageResponse);
    }

    //新增用户
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult insertUser(UserDto userDto) {
        //如果不是最底层的部门，则不允许添加
        if (isLowerDept(userDto.getDeptNo())){
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }
        //将用户添加到用户表中
        User user = BeanUtil.toBean(userDto, User.class);
        user.setNickName(userDto.getRealName());
        user.setUsername(userDto.getEmail());
        user.setDataState(userDto.getDataState());
        user.setPassword("123456");
        userMapper.insertSelective(user);
        //将数据插入到用户角色关系表中
        Set<String> roleVoIds = userDto.getRoleVoIds();
        List<UserRole> userRoleList = roleVoIds.stream().map(roleId -> {
            return UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(roleId))
                    .dataState(userDto.getDataState())
                    .build();
        }).collect(Collectors.toList());
        userRoleMapper.batchInsert(userRoleList);
        return ResponseResult.success(true);
    }

    //判断当前是否是最底层的部门
    private boolean isLowerDept(String deptNo) {
        String s = NoProcessing.processString(deptNo);
       List<Dept> list = deptMapper.findDeptByDeptNo(s);
       if (ObjectUtil.isEmpty(list)){
           return false;
        }
       return true;
    }

//    修改用户
    @Override
    public ResponseResult updateUser(UserDto userDto) {
        //用户信息直接修改
        User user = BeanUtil.toBean(userDto, User.class);
        userMapper.updateByPrimaryKeySelective(user);
        //关联的角色表先删除再修改,此处前端已经校验过了，穿过来的必须是不为空的
        Set<String> roleVoIds = userDto.getRoleVoIds();
        if (!EmptyUtil.isNullOrEmpty(roleVoIds)){
            userRoleMapper.deleteRoleByUserId(user.getId());
            List<UserRole> userRoleList = roleVoIds.stream().map(roleVoId -> {
                return UserRole.builder()
                        .userId(user.getId())
                        .roleId(Long.valueOf(roleVoId))
                        .dataState(userDto.getDataState())
                        .build();
            }).collect(Collectors.toList());
            userRoleMapper.batchInsert(userRoleList);
        }
        return ResponseResult.success(true);
    }

    //查询用户
    @Override
    public ResponseResult<UserVo> findUserVoList(UserDto userDto) {
        List<UserVo> userVoList = userMapper.findUserVoList(userDto);
        return ResponseResult.success(userVoList);
    }


    //修改用户状态
    @Override
    public void updateUserStatus(Long id, String status) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            throw new BaseException(BasicEnum.USER_EMPTY_EXCEPTION);
        }
        user.setDataState(status);
        userMapper.updateByPrimaryKeySelective(user);
    }


//    删除用户
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteUser(Long userId) {
        //删除角色用户表
        userRoleMapper.deleteRoleByUserId(userId);
        //秩序逻辑删除即可
        userMapper.deleteByPrimaryKey(userId);
        return ResponseResult.success();
    }

    //重置密码
    @Override
    public ResponseResult resetPassword(Long userId) {
        User user = new User();
        user.setPassword("123456");
        user.setId(userId);
        userMapper.updateByPrimaryKeySelective(user);
        return ResponseResult.success(true);
    }
}
